package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import sun.security.jca.ServiceId;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器类型，pre，routing，post，error
    @Override
    public String filterType() {
        return "pre";
    }
    //设置过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //针对当前请求，是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        //获取上下文对象
        RequestContext ctx=RequestContext.getCurrentContext();
        //从上下文对象获取调用的服务id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //获取请求上下文对象
        RequestContext ctx=RequestContext.getCurrentContext();
        //从上下文获得request对象
        HttpServletRequest request = ctx.getRequest();
        //从request取出token参数
        String token = request.getParameter("token");
        //如果没有token
        if (StringUtils.isBlank(token)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);
            //直接向客户端返回响应
            String json= JsonResult.build().code(400).msg("未登录！").toString();
            ctx.addZuulRequestHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }

        return null;//当前zuul版本中这个返回值不起任何作用
    }
}
